package taskscheduleservicelogic

import (
	"context"
	"github.com/jinzhu/copier"
	"go-zero-admin/application/job/rpc/internal/model"
	"go-zero-admin/application/job/rpc/internal/svc"
	job "go-zero-admin/application/job/rpc/pb"
	"go-zero-admin/pkg/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateCronLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateCronLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCronLogic {
	return &UpdateCronLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新定时任务接口
func (l *UpdateCronLogic) UpdateCron(in *job.UpdateCronReq) (*job.UpdateCronRes, error) {
	var res job.UpdateCronRes
	var mo model.TaskSchedule
	_ = copier.Copy(&mo, in.UpdateCronInfo)
	mo.ID = int64(in.UpdateCronInfo.TaskId)
	if err := l.svcCtx.DB.Where("id = ?", in.UpdateCronInfo.TaskId).Omit("created_at").Save(&mo).Error; err != nil {
		return nil, err
	}
	res.TaskScheduleInfo = &job.TaskScheduleInfo{}
	_ = copier.Copy(&res.TaskScheduleInfo, &mo)
	res.TaskScheduleInfo.CreatedAt = utils.SafeUnix(&mo.CreatedAt)
	res.TaskScheduleInfo.UpdatedAt = utils.SafeUnix(&mo.UpdatedAt)
	res.TaskScheduleInfo.LastExecuteTime = utils.SafeUnix(mo.LastExecuteTime)
	return &res, nil
}
